<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

const getRouterData = () => {
  let path = '/'
  if (Array.isArray(route.params.page)) {
    path += route.params.page.join('/')
  }
  return {
    path,
    query: route.query,
  }
}

const appData = ref({})
const changeChildAppRoute = (data) => {
  appData.value = {
    type: 'router',
    time: new Date().getTime(),
    data: data,
  }
}

watch(
  route,
  () => {
    changeChildAppRoute(getRouterData())
  },
  {
    deep: true,
  },
)
const asyncMainAppRoute = (data) => {
  const basePath = '/' + route.path.split('/').filter((i) => i)[0]
  if (typeof data === 'string') {
    router.push(basePath + data)
  } else {
    const { path, query } = data
    const renderPath = path.startsWith('/') ? path : '/' + path
    router.push({
      path: basePath + renderPath,
      query,
    })
  }
}

const onBeforeMount = () => {
  console.log('onBeforeMount')
  /*let index = 0
  setInterval(() => {
    if (index >= routerData.length) {
      index = 0
    }
    appData.value = routerData[index]
    index++
  }, 2000)*/
}

const onCreated = ()=>{
  console.log('onCreated')
}
const onBeforeshow = ()=>{
  console.log('onBeforeshow')
  changeChildAppRoute(getRouterData())
}
const onUnmount = ()=>{
  console.log('onUnmount')
}
const onError = ()=>{
  console.log('onError')
}
const onDataChange = (e) => {
  // 跳转页面
  const { type, data } = e.detail.data
  const methodMap = {
    routerChange(data) {
      // 在这里校验权限
      console.log('检验权限')
      asyncMainAppRoute(data)
      changeChildAppRoute(data)
    },
  }
  const method = methodMap[type]
  if (method) {
    method(data)
  }
}
</script>

<template>
  <div class="micro-app">
    <micro-app
      name="vue3"
      url="http://192.168.137.1:8000/"
      url1="https://zeroing.jd.com/micro-app/vue3"
      router-mode="state"
      iframe
      :data="appData"
      keep-alive
      @datachange="onDataChange"

      @created="onCreated"
      @beforemount="onBeforeMount"
      @mounted="onMounted"
      @unmount="onUnmount"
      @error="onError"
      @beforeshow='onBeforeshow'
    >
    </micro-app>
  </div>
</template>

<style scoped>
.micro-app {
  height: 500px;
  background-color: darkgrey;
  position: relative;
}

micro-app {
  height: 100%;
}
</style>
